package com.qf.controller;

import com.qf.captcha.CaptchaCodeManager;
import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.Base64;
import com.qf.util.ResponseUtil;
import com.qf.util.UUID;
import com.qf.util.VerifyCodeUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/admin/auth")
public class DtsAdminAuthController {

    @Autowired
    DtsRoleService roleService;

    @Autowired
    DtsPermissionService permissionService;


    @GetMapping("/info")
    public Object info(){
        Subject subject = SecurityUtils.getSubject();
        DtsAdmin admin = (DtsAdmin) subject.getPrincipal();

        Map<String,Object> data = new HashMap<>();
        Set<String> roles = roleService.findRoleByIds(admin.getRoleIds());
        data.put("roles",roles);
        data.put("name", admin.getUsername());
        Set<String> perms = permissionService.findPermByIds(admin.getRoleIds());
        data.put("perms",perms);
        data.put("avatar", admin.getAvatar());

        return ResponseUtil.ok(data);
    }



    @RequestMapping("/login")
    public Object login(@RequestBody Map<String,String> map, HttpSession session){
        String code = map.get("code");
        String password = map.get("password");
        String username = map.get("username");
        String uuid = map.get("uuid");

        String cachedCaptcha = CaptchaCodeManager.getCachedCaptcha(uuid);
        if(code == null || !code.equalsIgnoreCase(cachedCaptcha)) {
            return ResponseUtil.fail(-1, "验证码已过期或验证码错误!!");
        }


        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(username,password);

        try {
            subject.login(token);
        } catch (UnknownAccountException  e) {
            e.printStackTrace();
            return ResponseUtil.fail(-1, "未知的账户");
        } catch (LockedAccountException e){
            e.printStackTrace();
            return ResponseUtil.fail(-1, "账户已锁定");
        } catch (CredentialsException e){
            e.printStackTrace();
            return ResponseUtil.fail(-1, "密码错误");
        }


        System.out.println(subject.hasRole("超级管理员"));
        System.out.println(subject.isPermitted("admin:category:read"));

        return ResponseUtil.ok(session.getId());
    }


    @GetMapping("/captchaImage")
    public Object captchaImage() throws IOException {
        String code = VerifyCodeUtils.generateVerifyCode(2);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        VerifyCodeUtils.outputImage(111,33,outputStream ,code);

        String uuid = UUID.randomUUID().toString();
        CaptchaCodeManager.addToCache(uuid, code, 5 );


        Map<String,Object> data = new HashMap<>();
        data.put("img", Base64.encode(outputStream.toByteArray()));
        data.put("uuid",  uuid);

        return ResponseUtil.ok(data);
    }
}
